import React, { useState, useContext, useEffect } from "react";
import {
  Box,
  Flex,
  Slider,
  SliderTrack,
  SliderFilledTrack,
  SliderThumb,
  Radio,
  RadioGroup,
  Checkbox,
  Text,
  Stack,
  MenuButton,
  MenuList,
  MenuItem,
  Menu,
  Button,
  useDisclosure,
  useToast,
} from "@chakra-ui/react";
import { MainContext } from "@/src/providers/MainProvider";
import { MouseConfigInfo } from "@/src/types/types";
import { useTranslation } from "@/src/i18n";
import SettingBox from "./Common/SettingBox";
import { ChevronDownIcon } from "@chakra-ui/icons";
import MouseInfoToast from "../Common/MouseInfoToast";

interface WakeUpItem {
  label: string;
  value: number;
}

interface LodItem {
  value: string;
  checked: boolean;
}

const PerformanceSetting = () => {
  const {
    connectedMouse,
    mouseConfigInfo,
    setMouseConfigInfo,
    mouseReportRate,
    profile,
    profileIndex,
    connectMode,
  } = useContext(MainContext);

  // 轮询率设置
  const [reportRates] = useState([
    { label: "125", value: 0 },
    { label: "250", value: 1 },
    { label: "500", value: 2 },
    { label: "1000", value: 3 },
  ]);
  const { t } = useTranslation("");
  // 滚轮方向
  const [scrollFlags, setScrollFlags] = useState([]);
  // LOD静默高度
  const [lodSettings, setLodSettings] = useState<LodItem[]>([
    { value: "1mm", checked: false },
    { value: "2mm", checked: false },
  ]);

  // 当前轮询率
  const [currentReportRate, setCurrentReportRate] = useState(3);
  // 当前滚轮方向
  const [currentScrollFlag, setCurrentScrollFlag] = useState(0);
  // 当前唤醒方式
  const [currentWakeUpFlag, setCurrentWakeUpFlag] = useState(0);
  // 当前灯光开启方式
  const [currentMoveLightFlag, setCurrentMoveLightFlag] = useState(0);

  // 唤醒方式
  const [wakeUpSettings, setWakeUpSettings] = useState<WakeUpItem[]>([
    { label: t("keyWakeUp"), value: 0 },
    { label: t("moveWakeUp"), value: 1 },
  ]);

  // 灯光开启方式
  const [turnLightsSettings, setTurnLightsSettings] = useState<WakeUpItem[]>([
    { label: t("lightLabel1"), value: 0 },
    { label: t("lightLabel2"), value: 1 },
  ]);

  // 灯光模式
  const [lightModeValue, setLightModeValue] = useState<number>(0);
  const toast = useToast();

  useEffect(() => {
    setScrollFlags([
      { label: t("forwardDirection"), value: 0 },
      { label: t("reverseDirection"), value: 1 },
    ]);
  }, [t]);

  // 休眠时间
  const [sleepTime, setSleepTime] = useState<number>(10);
  const [sleepTime2, setSleepTime2] = useState<number>(10);
  // 无休眠状态
  const [noSleepStatus, setNoSleepStatus] = useState<boolean>(false);

  const [lightModes] = useState([
    { label: t("lightMode1"), value: 0 },
    { label: t("lightMode2"), value: 1 },
    { label: t("lightMode3"), value: 2 },
    { label: t("lightMode4"), value: 3 },
    { label: t("lightMode5"), value: 4 },
    { label: t("lightMode6"), value: 5 },
    { label: t("lightMode7"), value: 6 },
    { label: t("lightMode8"), value: 7 },
    { label: t("lightMode9"), value: 8 },
    { label: t("lightMode10"), value: 9 },
  ]);

  const {
    isOpen: isDpiMenuOpen,
    onOpen: onDpiMenuOpen,
    onClose: onDpiMenuClose,
  } = useDisclosure();

  // 初始化更新配置
  const UpdateMouseConfig = (configInfo: MouseConfigInfo) => {
    console.log("updateMouseConfig", configInfo);
    // 更新休眠设置
    setSleepTime(configInfo.sleep_light);
    if (sleepTime2 == 10) {
      setSleepTime2(configInfo.sleep_light == 0 ? 10 : configInfo.sleep_light);
    }
    setNoSleepStatus(configInfo.sleep_light === 0);
    // 更新轮询率设置
    setCurrentReportRate(configInfo.report_rate);
    // 设置滚轮方向
    setCurrentScrollFlag(configInfo.scroll_flag);
    // 设置唤醒方式
    setCurrentWakeUpFlag(configInfo.wakeup_flag);
    // 设置灯光开启方式
    setCurrentMoveLightFlag(configInfo.move_light_flag);
    // 设置灯光模式
    setLightModeValue(configInfo.light_mode);

    // 更新 LOD 设置
    setLodSettings((prev) =>
      prev.map((item, index) => ({
        ...item,
        checked: index === configInfo.lod_value - 1,
      }))
    );
  };

  // 添加安全配置更新函数
  const safeUpdateMouseConfig = async (
    partialConfig: Partial<MouseConfigInfo>
  ) => {
    if (!connectedMouse || !mouseConfigInfo) {
      console.warn("connectedMouse or mouseConfigInfo is null");
      return;
    }

    try {
      // 获取设备当前完整配置，确保DPI信息是最新的
      const currentDeviceConfig = await connectedMouse.getMouseConfigInfo();

      // 合并配置：使用设备当前的DPI配置 + 新的性能设置
      const mergedConfig = {
        ...mouseConfigInfo,
        // 保留设备当前的DPI配置
        dpi_index: currentDeviceConfig?.dpi_index ?? mouseConfigInfo.dpi_index,
        dpi_count: currentDeviceConfig?.dpi_count ?? mouseConfigInfo.dpi_count,
        dpi1_value:
          currentDeviceConfig?.dpi1_value ?? mouseConfigInfo.dpi1_value,
        dpi2_value:
          currentDeviceConfig?.dpi2_value ?? mouseConfigInfo.dpi2_value,
        dpi3_value:
          currentDeviceConfig?.dpi3_value ?? mouseConfigInfo.dpi3_value,
        dpi4_value:
          currentDeviceConfig?.dpi4_value ?? mouseConfigInfo.dpi4_value,
        dpi5_value:
          currentDeviceConfig?.dpi5_value ?? mouseConfigInfo.dpi5_value,
        dpi6_value:
          currentDeviceConfig?.dpi6_value ?? mouseConfigInfo.dpi6_value,
        profile_index:
          currentDeviceConfig?.profile_index ?? mouseConfigInfo.profile_index,
        // 应用新的性能设置
        ...partialConfig,
      };

      // 更新本地状态
      setMouseConfigInfo(mergedConfig);

      // 更新配置文件
      if (profile) {
        profile.updateMouseConfig(profileIndex, mergedConfig);
      }

      // 发送到设备
      await connectedMouse.setMouseConfigData(mergedConfig);

      console.log("配置更新成功:", partialConfig);
    } catch (error) {
      console.error("配置更新失败:", error);
      // 如果获取设备配置失败，则使用当前配置进行更新
      const fallbackConfig = {
        ...mouseConfigInfo,
        ...partialConfig,
      };

      setMouseConfigInfo(fallbackConfig);
      if (profile) {
        profile.updateMouseConfig(profileIndex, fallbackConfig);
      }
      await connectedMouse.setMouseConfigData(fallbackConfig);
    }
  };

  // 唤醒方式设置
  const handleWakeUpChange = async (value: string) => {
    const wakeUpFlag = parseInt(value);
    setCurrentWakeUpFlag(wakeUpFlag);

    await safeUpdateMouseConfig({
      wakeup_flag: wakeUpFlag,
    });
  };

  // 灯光开启方式设置
  const handleTurnLightsChange = async (value: string) => {
    const moveLightFlag = parseInt(value);

    setCurrentMoveLightFlag(moveLightFlag);

    await safeUpdateMouseConfig({
      move_light_flag: moveLightFlag,
    });
  };

  // 休眠设置 - 实时更新
  const handleSliderSleepTimeChange = (value: number) => {
    setSleepTime(value);
    if (value === 0) {
      setNoSleepStatus(true);
    } else {
      setNoSleepStatus(false);
    }
  };

  // 休眠设置 - 完成更新
  const handleSliderSleepTimeChangeEnd = async (value: number) => {
    setSleepTime(value);
    setSleepTime2(value == 0 ? 10 : value);

    if (value === 0) {
      setNoSleepStatus(true);
    } else {
      setNoSleepStatus(false);
    }

    await safeUpdateMouseConfig({
      sleep_light: value,
    });
  };

  // 休眠时间 - 单选框状态
  const handleRadioSleepTimeChange = async (value: boolean) => {
    setNoSleepStatus(value);
    setSleepTime(value ? 0 : sleepTime2);

    await safeUpdateMouseConfig({
      sleep_light: value ? 0 : sleepTime2,
    });
  };

  // 回报率设置
  const handlePollingRateChange = async (value: string) => {
    const newReportRate = parseInt(value);
    setCurrentReportRate(newReportRate);

    await safeUpdateMouseConfig({
      report_rate: newReportRate,
    });

    if (mouseConfigInfo) {
      const currentDpiValue =
        (mouseConfigInfo[
          `dpi${mouseConfigInfo.dpi_index + 1}_value` as keyof MouseConfigInfo
        ] as number) || 800;

      toast({
        title: t("mouseInfoUpdated"),
        status: "success",
        duration: 3000,
        position: "bottom-right",
        render: () => (
          <MouseInfoToast
            data={{
              dpiLevel: mouseConfigInfo.dpi_index + 1,
              dpiValue: currentDpiValue,
              reportRate:
                newReportRate === 0
                  ? 125
                  : newReportRate === 1
                  ? 250
                  : newReportRate === 2
                  ? 500
                  : 1000,
            }}
          />
        ),
      });
    }
  };

  // 滚轮方向设置
  const handleScrollFlagChange = async (value: string) => {
    setCurrentScrollFlag(parseInt(value));

    await safeUpdateMouseConfig({
      scroll_flag: parseInt(value),
    });
  };

  // 静默高度
  const handleLodChange = async (index: number) => {
    setLodSettings((prev) =>
      prev.map((item, i) => ({ ...item, checked: i === index }))
    );

    await safeUpdateMouseConfig({
      lod_value: index + 1,
    });
  };

  const changeLightMode = (index: number) => {
    // 选择项后关闭菜单
    onDpiMenuClose();

    setLightModeValue(index);

    if (connectedMouse && mouseConfigInfo) {
      const mouseconfig_ = mouseConfigInfo;

      mouseconfig_.light_mode = index;

      setMouseConfigInfo(mouseconfig_);
      connectedMouse.setLightMode(index);
    }
  };

  useEffect(() => {
    if (mouseConfigInfo) {
      UpdateMouseConfig(mouseConfigInfo);
    }
  }, [mouseConfigInfo]);

  useEffect(() => {
    setCurrentReportRate(mouseReportRate);
  }, [mouseReportRate]);

  return (
    <Box pl="0px" pr="0px" pb="0px">
      <Flex gap={6}>
        {/* 左侧设置项 */}
        <Box flex="1" display="flex" flexDirection="column" gap={6}>
          {/* 灯光开启方式 */}
          <SettingBox title={t("turnLights")} description={t("turnLightsTip")}>
            <Flex gap={6}>
              <RadioGroup
                value={currentMoveLightFlag?.toString()}
                onChange={handleTurnLightsChange}
              >
                <Stack direction="row" spacing={4}>
                  {turnLightsSettings.map((turnLights, i) => (
                    <Radio
                      key={turnLights.value.toString()}
                      value={turnLights.value.toString()}
                    >
                      <Text
                        ml={2}
                        color="white"
                        fontFamily="Microsoft YaHei"
                        fontSize="13px"
                        fontWeight={400}
                      >
                        {turnLights.label}
                      </Text>
                    </Radio>
                  ))}
                </Stack>
              </RadioGroup>
            </Flex>
          </SettingBox>
          {/* 休眠设置 */}
          <SettingBox
            title={t("sleepSetting") + "（" + t("minute") + "）"}
            description={t("sleepTip")}
          >
            <Flex align="center">
              <Box flex="1" position="relative" mr={8}>
                <Slider
                  value={sleepTime}
                  onChange={handleSliderSleepTimeChange}
                  onChangeEnd={handleSliderSleepTimeChangeEnd}
                  min={0}
                  max={100}
                  colorScheme="orange"
                  step={1}
                >
                  <SliderTrack>
                    <SliderFilledTrack bg="#0066ff" />
                  </SliderTrack>
                  <SliderThumb boxSize={4} bg="#0066ff" />
                </Slider>
                <Text position="absolute" bottom="-15px" left="0" color="white">
                  {sleepTime} {t("minute")}
                </Text>
              </Box>
              <Flex align="center">
                <Checkbox
                  isChecked={noSleepStatus}
                  onChange={() => handleRadioSleepTimeChange(!noSleepStatus)}
                />
                <Text ml={2} color="white">
                  {t("neverSleep")}
                </Text>
              </Flex>
            </Flex>
          </SettingBox>

          {/* 轮询率设置 */}
          <SettingBox
            title={t("pollingRateSetting") + "（Hz）"}
            description={t("pollingTip")}
          >
            <RadioGroup
              value={currentReportRate.toString()}
              onChange={handlePollingRateChange}
            >
              <Stack direction="row" spacing={4}>
                {connectMode != "有线连接" &&
                  reportRates.map((rate) => (
                    <Radio
                      key={rate.value.toString()}
                      value={rate.value.toString()}
                    >
                      <Text
                        color="white"
                        fontFamily="Microsoft YaHei"
                        fontSize="13px"
                        fontWeight={400}
                      >
                        {rate.label}
                      </Text>
                    </Radio>
                  ))}
                {connectMode == "有线连接" && (
                  <Radio defaultChecked>
                    <Text
                      color="white"
                      fontFamily="Microsoft YaHei"
                      fontSize="13px"
                      fontWeight={400}
                    >
                      1000
                    </Text>
                  </Radio>
                )}
              </Stack>
            </RadioGroup>
          </SettingBox>

          {/* 唤醒方式 */}
          <SettingBox title={t("wakeUp")} description={t("wakeUpTip")}>
            <Flex gap={6}>
              <RadioGroup
                value={currentWakeUpFlag?.toString()}
                onChange={handleWakeUpChange}
              >
                <Stack direction="row" spacing={4}>
                  {wakeUpSettings.map((wakeUp, i) => (
                    <Radio
                      key={wakeUp.value.toString()}
                      value={wakeUp.value.toString()}
                    >
                      <Text
                        ml={2}
                        color="white"
                        fontFamily="Microsoft YaHei"
                        fontSize="13px"
                        fontWeight={400}
                      >
                        {wakeUp.label}
                      </Text>
                    </Radio>
                  ))}
                </Stack>
              </RadioGroup>
            </Flex>
          </SettingBox>
        </Box>

        {/* 右侧设置项 */}
        <Box flex="1" display="flex" flexDirection="column" gap={6}>
          {/* 灯光模式 */}
          <SettingBox
            title={t("lightSetting")}
            description={t("lightSettingTip")}
          >
            <Menu
              isOpen={isDpiMenuOpen}
              onClose={onDpiMenuClose}
              closeOnBlur={true}
              closeOnSelect={false}
            >
              <MenuButton
                as={Button}
                rightIcon={
                  <Box
                    as={ChevronDownIcon}
                    transition="transform 0.2s ease"
                    transform={
                      isDpiMenuOpen ? "rotate(180deg)" : "rotate(0deg)"
                    }
                  />
                }
                minW="140px"
                height="40px"
                size="lg"
                fontSize="14px"
                bg="#262626"
                borderColor="#2B2B2B"
                textAlign={"left"}
                borderWidth="1px"
                padding="0 12px"
                onClick={(e) => {
                  // 阻止二次点击时的默认关闭行为
                  e.preventDefault();
                  if (!isDpiMenuOpen) {
                    onDpiMenuOpen();
                  }
                }}
                _focus={{
                  borderColor: "brand.200",
                  boxShadow: "0 0 0 1px brand.200",
                }}
                _hover={{
                  bg: "#262626",
                }}
                _active={{
                  bg: "#262626",
                }}
                fontWeight="normal"
                justifyContent="space-between"
              >
                {
                  lightModes.find((option) => option.value === lightModeValue)
                    ?.label
                }
              </MenuButton>
              <MenuList
                border="none"
                boxShadow="lg"
                bg="#262626"
                minW="140px"
                pl="0"
              >
                {lightModes.map((option) => (
                  <MenuItem
                    key={option.value}
                    onClick={() => changeLightMode(option.value)}
                    fontSize="14px"
                    bg="#262626"
                    color={
                      option.value === lightModeValue ? "#0066ff" : "#ffffff"
                    }
                    fontWeight={
                      option.value === lightModeValue ? "bold" : "normal"
                    }
                    _hover={{
                      bg: "#2b2d31",
                    }}
                  >
                    {option.label}
                  </MenuItem>
                ))}
              </MenuList>
            </Menu>
          </SettingBox>

          {/* 滚轮方向 */}
          <SettingBox
            title={t("rollerDirection")}
            description={t("rollerDirectionTip")}
          >
            <RadioGroup
              value={currentScrollFlag?.toString()}
              onChange={handleScrollFlagChange}
            >
              <Stack direction="row" spacing={4}>
                {scrollFlags.map((flag) => (
                  <Radio
                    key={flag.value.toString()}
                    value={flag.value.toString()}
                  >
                    <Text
                      color="white"
                      fontFamily="Microsoft YaHei"
                      fontSize="13px"
                      fontWeight={400}
                    >
                      {flag.label}
                    </Text>
                  </Radio>
                ))}
              </Stack>
            </RadioGroup>
          </SettingBox>

          {/* LOD静默高度 */}
          <SettingBox
            title={t("lODSilentHeight")}
            description={t("lODSilentHeightTip")}
          >
            <Flex gap={6}>
              {lodSettings.map((lod, i) => (
                <Flex key={i} align="center">
                  <Radio
                    isChecked={lod.checked}
                    onChange={() => handleLodChange(i)}
                  />
                  <Text
                    ml={2}
                    color="white"
                    fontFamily="Microsoft YaHei"
                    fontSize="13px"
                    fontWeight={400}
                  >
                    {lod.value}
                  </Text>
                </Flex>
              ))}
            </Flex>
          </SettingBox>
        </Box>
      </Flex>
    </Box>
  );
};

export default PerformanceSetting;
